const { ipcMain, dialog } = require('electron');
const fs = require('fs').promises;
const path = require('path');

// 处理文件夹选择对话框
ipcMain.handle('open-folder-dialog', async () => {
    return await dialog.showOpenDialog({
        properties: ['openDirectory'],
        title: '选择项目目录',
        buttonLabel: '选择此目录'
    });
});

// 目录读取方法
ipcMain.handle('read-dir', async (_, dirPath) => {
    try {
        const items = await fs.readdir(dirPath);
        return Promise.all(items.map(async item => {
            const fullPath = path.join(dirPath, item);
            const stats = await fs.stat(fullPath);

            // 添加 path 属性存储绝对路径
            return {
                name: item,
                type: stats.isDirectory() ? 'directory' : 'file',
                path: fullPath  // 新增的绝对路径属性
            };
        }));
    } catch (error) {
        console.error('目录读取错误:', error);
        return [];
    }
});

// 创建文件夹
ipcMain.handle('create-directory', async (_, dirPath) => {
    try {
        await fs.mkdir(dirPath, { recursive: true });
        return { success: true };
    } catch (error) {
        console.error('创建文件夹失败:', error);
        return { success: false, error: error.message };
    }
});

// 重命名文件或文件夹
ipcMain.handle('rename-file-or-dir', async (_, oldPath, newName) => {
    try {
        const dirPath = path.dirname(oldPath);
        const newPath = path.join(dirPath, newName);
        await fs.rename(oldPath, newPath);
        return { success: true, newPath: newPath };
    } catch (error) {
        console.error('重命名失败:', error);
        return { success: false, error: error.message };
    }
});

// 删除文件或文件夹
ipcMain.handle('delete-file-or-dir', async (_, filePath) => {
    try {
        await fs.rm(filePath, { recursive: true });
        return { success: true };
    } catch (error) {
        console.error('删除文件或文件夹失败:', error);
        return { success: false, error: error.message };
    }
});

//读取文本文件内容
ipcMain.handle('read-text-file', async (_, filePath) => {
    try {
        return await fs.readFile(filePath, 'utf-8');
    } catch (error) {
        console.error('读取文本文件失败:', error);
        return null;
    }
});

// 修改文件内容
ipcMain.handle('write-text-file', async (_, filePath, content) => {
    try {
        await fs.writeFile(filePath, content, 'utf-8');
        return { success: true };
    } catch (error) {
        console.error('写入文件失败:', error);
        return { success: false, error: error.message };
    }
});

// 移动文件或文件夹
ipcMain.handle('move-file-or-dir', async (_, sourcePath, targetPath) => {
    try {
        // 检查目标路径是否是目录，如果是，则将源文件移动到该目录下
        const targetStats = await fs.stat(targetPath).catch(() => null);
        if (targetStats && targetStats.isDirectory()) {
            const fileName = path.basename(sourcePath);
            const newTargetPath = path.join(targetPath, fileName);
            await fs.rename(sourcePath, newTargetPath);
        } else {
            await fs.rename(sourcePath, targetPath);
        }
        return { success: true };
    } catch (error) {
        console.error('移动文件或文件夹失败:', error);
        return { success: false, error: error.message };
    }
});
